//
//  MakeInquiryViewController.m
//  Logistics
//
//  Created by hy002 on 2018/1/10.
//  Copyright © 2018年 HUYU. All rights reserved.
//

#import "MakeInquiryViewController.h"
#import "GoodsAddressModel.h"
#import "CloseGoodsAddressViewController.h"

static NSString *cellPath = @"inquiryCell";
@interface MakeInquiryViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIScrollViewDelegate,UIPickerViewDelegate,UIPickerViewDataSource>
{
    UIPickerView *pickTypeView;
}
@property (nonatomic,strong)UIView *TypeView;
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)NSArray *titAry;
@property (nonatomic, strong)NSArray *imgAry;
@property (nonatomic, strong)NSString *goodsName;
@property (nonatomic, strong)NSString *volume;
@property (nonatomic, strong)NSString *weight;
@property (nonatomic, strong)NSString *name;
@property (nonatomic, strong)NSString *phone;
@property (nonatomic, strong)NSArray *typeAry;
@property (nonatomic, strong)NSString *startAddress;
@property (nonatomic, strong)NSString *stopAddress;


@end

@implementation MakeInquiryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _goodsName = @"";
    _volume = @"";
    _weight = @"";
    _name = @"";
    _phone = @"";
    _startAddress = @"";
    _stopAddress = @"";
    _titAry = @[@"装货地址",@"卸货地址",@"货物类型",@"体积",@"重量",@"发货人",@"电话"];
    _imgAry = @[@"lb_icon012",@"lb_icon13",@"lb_icon14",@"lb_icon15",@"lb_icon16",@"lb_icon17",@"lb_icon18"];
    [self creatUI];
    [self requestCargoType];
}

- (void)creatUI
{
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"询价";
    self.view.backgroundColor = BacksColor;
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(15*displaywidth, 15*displaywidth, SCREEN_WIDTH-30*displaywidth, 350*displaywidth) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.layer.cornerRadius = 10;
    _tableview.layer.masksToBounds = YES;
    [self.view addSubview:_tableview];
    UILabel *tostLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 370*displaywidth, SCREEN_WIDTH-30*displaywidth, 30*displaywidth) Font:12.0 Text:@"下单后请保持通讯畅通，我们将第一时间与您取得联系" Color:RGB(178, 178, 178)];
    tostLab.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:tostLab];
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-STA_NAV_HEIGHT-SCREER_HeiX-65*displaywidth, SCREEN_WIDTH, 65*displaywidth+SCREER_HeiX)];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];
    UIButton *soureBtn = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth, 10*displaywidth, SCREEN_WIDTH-30*displaywidth, 45*displaywidth) ImageName:nil Target:self Action:@selector(soureBtnAction) Title:@"提交" Font:16.0];
    soureBtn.backgroundColor = RGB(255, 153, 0);
    [soureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    soureBtn.layer.cornerRadius = 5;
    soureBtn.layer.masksToBounds = YES;
    [bottomView addSubview:soureBtn];
}

- (void)companyAction
{
    if (!self.TypeView)
    {
        self.TypeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT)];
        _TypeView.backgroundColor = RGBA(0, 0, 0, 0.6);
        [self.view addSubview:_TypeView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bottomViewPressed)];
        [_TypeView addGestureRecognizer:tap];
        pickTypeView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-250*displayheight-STA_NAV_HEIGHT, SCREEN_WIDTH, 250*displayheight)];
        pickTypeView.backgroundColor = [UIColor whiteColor];
        pickTypeView.delegate = self;
        pickTypeView.dataSource = self;
        [_TypeView addSubview:pickTypeView];
        UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-280*displayheight-STA_NAV_HEIGHT, SCREEN_WIDTH, 30*displayheight)];
        whiteView.backgroundColor = [UIColor whiteColor];
        [_TypeView addSubview:whiteView];
        UIButton *cancelBtn = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth, 10*displayheight, 40*displaywidth, 20*displayheight) ImageName:nil Target:self Action:@selector(bottomViewPressed) Title:@"取消" Font:13.0];
        cancelBtn.backgroundColor = ThemeColor;
        [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        cancelBtn.layer.cornerRadius = 3;
        cancelBtn.layer.masksToBounds = YES;
        [whiteView addSubview:cancelBtn];
        
        UIButton *soureBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH- 55*displaywidth, 10*displayheight, 40*displaywidth, 20*displayheight) ImageName:nil Target:self Action:@selector(soureAction) Title:@"确定" Font:13.0];
        soureBtn.backgroundColor = ThemeColor;
        [soureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        soureBtn.layer.cornerRadius = 3;
        soureBtn.layer.masksToBounds = YES;
        [whiteView addSubview:soureBtn];
        
    }
    _TypeView.hidden = NO;
    
    
}

- (void)soureAction
{
    NSInteger selectRow = [pickTypeView selectedRowInComponent:0];
    GoodsAddressModel *model = _typeAry[selectRow];
    _goodsName = model.name;
    [self bottomViewPressed];
    [_tableview reloadData];
}


- (void)bottomViewPressed
{
    _TypeView.hidden = YES;
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

//指定每个表盘上有几行数据
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return _typeAry.count;
}

#pragma mark UIPickerView Delegate Method 代理方法

//指定每行如何展示数据（此处和tableview类似）
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    GoodsAddressModel *model = _typeAry[row];
    return model.name;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSLog(@"%ld------%ld",component,row);
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _titAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSInteger index = indexPath.row;
    cell.imageView.image = IMAGE(_imgAry[index]);
    cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
    cell.textLabel.text = _titAry[index];
    cell.textLabel.font = NormalFontWithSize(17.0+fontScale);
    cell.textLabel.textColor = BlaTitColor;
    
    if (index > 2)
    {
        NSArray *textAry = @[@"",@"",@"",_volume,_weight,_name,_phone,@"",@""];
        UITextField *textfield = [ZCControl createTextFieldWithFrame:CGRectMake(SCREEN_WIDTH-230*displaywidth, 5*displaywidth, 185*displaywidth, 40*displaywidth) placeholder:@"" passWord:NO leftImageView:nil rightImageView:nil Font:14.0];
        textfield.textColor = BlaTitColor;
        textfield.delegate = self;
        textfield.tag = 10+index;
        textfield.text = textAry[index];
        if (index == 3)
        {
            textfield.placeholder = @"/立方";
            textfield.keyboardType = UIKeyboardTypeDecimalPad;
        }
        if (index == 4)
        {
            textfield.placeholder = @"/吨";
            textfield.keyboardType = UIKeyboardTypeDecimalPad;
        }
        if (index == 6)
        {
            textfield.keyboardType = UIKeyboardTypeDecimalPad;

        }
        textfield.textAlignment = NSTextAlignmentRight;
        [cell.contentView addSubview:textfield];
        
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        NSArray *nameAry = @[_startAddress,_stopAddress,_goodsName];
        UILabel *rightLab = [ZCControl createLabelWithFrame:CGRectMake(SCREEN_WIDTH-230*displaywidth, 5*displaywidth, 170*displaywidth, 40*displaywidth) Font:14.0 Text:nameAry[index] Color:BlaTitColor];
        rightLab.textAlignment = NSTextAlignmentRight;
        [cell.contentView addSubview:rightLab];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger index = indexPath.row;
    if (index == 0 || index == 1)
    {
        WEAKSELF;
        CloseGoodsAddressViewController *vc = [[CloseGoodsAddressViewController alloc] init];
        vc.areaType = index;
        vc.closeBlock = ^(NSString *name, NSInteger index)
        {
            if (index == 0)
            {
                _startAddress = name;
            }
            else
            {
                _stopAddress = name;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableview reloadData];
            });
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (index == 2)
    {
        [self companyAction];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50*displaywidth;
}

//提交
- (void)soureBtnAction
{
    [self.view endEditing:YES];
    NSArray *nameARRAY = @[_startAddress,_stopAddress,_goodsName,_volume,_weight,_name,_phone];
    NSArray *tostAry = @[@"请选择装货地址",@"请选择卸货地址",@"请选择货物类型",@"请输入体积",@"请输入重量",@"请输入发货人姓名",@"请输入电话"];
    for (int i = 0; i < nameARRAY.count; i++)
    {
        if ([nameARRAY[i] isEqualToString:@""])
        {
            [LTools showMBProgressWithText:tostAry[i] addToView:self.view];
            return;
        }
    }
    WEAKSELF;
    NSDictionary *dic = @{@"shipment":_startAddress,
                          @"destination":_stopAddress,
                          @"cargoName":_goodsName,
                          @"weight":_weight,
                          @"volume":_volume,
                          @"linkman":_name,
                          @"phone":_phone,
                          @"type":_typeStr,
                          @"company.id":_companyID};
    [HYBaseHandler requestWithTheFormUrl:SERVER_enquirySave Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            [LTools showMBProgressWithText:@"提交成功，已发送询价短信" addToView:sharedDelegate.window];
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

//类型
- (void)requestCargoType
{
    WEAKSELF;
    NSDictionary *dic = @{@"size":@"999"};
    [HYBaseHandler requestWithTheFormUrl:SERVER_cargoType Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            _typeAry = [GoodsAddressModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [pickTypeView reloadAllComponents];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField.tag == 12)
    {
        _goodsName = textField.text;
    }
    else if (textField.tag == 13)
    {
        _volume = textField.text;
    }
    else if (textField.tag == 14)
    {
        _weight = textField.text;
    }
    else if (textField.tag == 15)
    {
        _name = textField.text;
    }
    else if (textField.tag == 16)
    {
        _phone = textField.text;
    }
    _tableview.frame = CGRectMake(15*displaywidth, 15*displaywidth, SCREEN_WIDTH-30*displaywidth, 350*displaywidth);
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField.tag > 14)
    {
        _tableview.frame = CGRectMake(15*displaywidth, -100, SCREEN_WIDTH-30*displaywidth, 350*displaywidth);
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.view endEditing:YES];
    return indexPath;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
